package com.kaikeba.wechat.controller;

import com.kaikeba.bean.*;
import com.kaikeba.mvc.ResponseBody;
import com.kaikeba.service.ExpressService;
import com.kaikeba.service.impl.ExpressServiceImpl;
import com.kaikeba.util.FormatUtil;
import com.kaikeba.util.JsonUtil;
import com.kaikeba.util.UserSessionUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

public class ExpressController {

    private ExpressService service = new ExpressServiceImpl();

    @ResponseBody("/wx/findExpress.do")
    public String findExpress(HttpServletRequest req, HttpServletResponse resp){
        resp.setContentType("text/html;charset=utf-8");
        User user = UserSessionUtil.getUser(req.getSession());
        String userPhone = null;
        if (user!=null) {
            userPhone = user.getUserPhone();
        }else {
            Courier courier = UserSessionUtil.getCourier(req.getSession());
            if (courier!=null){
                userPhone = courier.getUserPhone();
            }
        }
        List<Express> userList = service.findByUserPhone(userPhone);
        List<BootstrpExpress> bList = new ArrayList<>();
        for (Express e : userList) {
            String inTime = FormatUtil.format(e.getInTime());
            String outTime = e.getOutTime()==null?"未出库":FormatUtil.format(e.getOutTime());
            String status = e.getStatus()==0?"待取件":"已取件";
            String code = e.getCode()==null?"已取件":e.getCode();
            BootstrpExpress e2 = new BootstrpExpress(e.getId(),e.getNumber(),e.getUserName(),e.getUserPhone(),e.getCompany(),code,inTime,outTime,status,e.getSysPhone());
            bList.add(e2);
        }

        Message message = new Message();
        if (userList.size()==0){
            message.setStatus(-1);
        }else {
            message.setStatus(0);
            //待取件数组
            Stream<BootstrpExpress> list0 = bList.stream().filter(express -> {
                if (express.getStatus().equals("待取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1, o2) -> {
                long o1Time = FormatUtil.toTime(o1.getInTime());
                long o2Time = FormatUtil.toTime(o2.getInTime());
                return (int) (o1Time - o2Time);
            });

            //已取件数组
            Stream<BootstrpExpress> list1 = bList.stream().filter(express -> {
                if (express.getStatus().equals("已取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1, o2) -> {
                long o1Time = FormatUtil.toTime(o1.getInTime());
                long o2Time = FormatUtil.toTime(o2.getInTime());
                return (int) (o1Time - o2Time);
            });

            //将stream流处理结果转换成数组
            Object[] object0 = list0.toArray();
            Object[] object1 = list1.toArray();
            Map data = new HashMap<>();
            data.put("status0",object0);
            data.put("status1",object1);
            message.setData(data);
        }

        String json = JsonUtil.toJson(message);
        return json;
    }

    /**
     * 根据扫描二维码得到的手机号码查询该用户的全部快递信息
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody("/wx/getExpressList.do")
    public String expressList(HttpServletRequest req, HttpServletResponse resp){
        resp.setContentType("text/html;charset=utf-8");
        String userPhone = req.getParameter("userPhone");
        //只获取未取件的快递
        List<Express> userList = service.findByUserPhoneAndStatus(userPhone,0);
        List<BootstrpExpress> bList = new ArrayList<>();
        for (Express e : userList) {
            String inTime = FormatUtil.format(e.getInTime());
            String outTime = e.getOutTime()==null?"未出库":FormatUtil.format(e.getOutTime());
            String status = e.getStatus()==0?"待取件":"已取件";
            String code = e.getCode()==null?"已取件":e.getCode();
            BootstrpExpress e2 = new BootstrpExpress(e.getId(),e.getNumber(),e.getUserName(),e.getUserPhone(),e.getCompany(),code,inTime,outTime,status,e.getSysPhone());
            bList.add(e2);
        }
        Message message = new Message();
        if (userList.size()==0){
            message.setStatus(-1);
            message.setResult("该手机号码暂无快递");
        }else {
            message.setStatus(0);
            message.setResult("查找成功");
            message.setData(bList);
        }
        return JsonUtil.toJson(message);
    }


    @ResponseBody("/wx/findExpressByCode.do")
    public String findExpressByCode(HttpServletRequest req, HttpServletResponse resp){
        resp.setContentType("text/html;charset=utf-8");
        String codes = req.getParameter("code");
        Express e  = service.findByCode(codes);
        BootstrpExpress bexpress = null;
        if (e!=null) {
            String inTime = FormatUtil.format(e.getInTime());
            String outTime = e.getOutTime() == null ? "未出库" : FormatUtil.format(e.getOutTime());
            String status = e.getStatus() == 0 ? "待取件" : "已取件";
            String code = e.getCode() == null ? "已取件" : e.getCode();
            bexpress = new BootstrpExpress(e.getId(), e.getNumber(), e.getUserName(), e.getUserPhone(), e.getCompany(), code, inTime, outTime, status, e.getSysPhone());
        }
        Message message = new Message();
        if (e!=null){
            message.setStatus(0);
            message.setResult("查找成功");
            message.setData(bexpress);
        }else {
            message.setStatus(-1);
            message.setResult("暂无此快递");
        }
        return JsonUtil.toJson(message);
    }

    @ResponseBody("/wx/updateStatus.do")
    public String updateStatus(HttpServletRequest req, HttpServletResponse resp){
        resp.setContentType("text/html;charset=utf-8");
        String code = req.getParameter("code");
        boolean update = service.updateStatus(code);
        Message message = new Message();
        if (update){
            message.setStatus(0);
            message.setResult("快递已取货");
        }else {
            message.setStatus(-1);
            message.setResult("取货异常，请稍后再试");
        }
        return JsonUtil.toJson(message);
    }

    @ResponseBody("/wx/addExpress.do")
    public String addExpress(HttpServletRequest req, HttpServletResponse resp){
        resp.setContentType("text/html;charset=utf-8");
        String number = req.getParameter("number");
        String userName = req.getParameter("userName");
        String phone = req.getParameter("phone");
        String company = req.getParameter("company");
        Courier courier = UserSessionUtil.getCourier(req.getSession());
        Express express = new Express(number,userName,phone,company,courier.getUserPhone());
        boolean insert = service.insert(express);
        Message message = new Message();
        if (insert){
            message.setStatus(0);
            message.setResult("录入成功");
        }else {
            message.setStatus(-1);
            message.setResult("录入失败");
        }
        return JsonUtil.toJson(message);
    }
}
